package com.wei.zuba.cfg;


import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


@Configuration
@EnableConfigurationProperties({
	DruidDSConfig.DruidDataSourcProperties.class})
@Slf4j
public class DruidDSConfig {

	@Autowired
	DruidDataSourcProperties dsProperties;

	@Bean
	public DataSource dataSource() {
		return createDataSource(dsProperties);
	}	
	
	@Bean
    public StatViewServlet druidStatView() {
        return new StatViewServlet();
    }
	
	private DataSource createDataSource(BaseDataSourcProperties properties) {
		DruidDataSource dataSource = null;
		try {
			dataSource = new DruidDataSource();
			dataSource.setUrl(properties.getUrl());
			dataSource.setUsername(properties.getUsername());
			dataSource.setPassword(properties.getPassword());
			dataSource.setFilters(properties.getFilters());
			dataSource.setInitialSize(properties.getInitialSize());
			dataSource.setMaxActive(properties.getMaxActive());
			dataSource.setMinIdle(properties.getMinIdle());
			// -- 配置监控统计拦截的filters --
			dataSource.addFilters(properties.filters);
		} catch (SQLException e) {
			log.error("Durid datasource initailized failed!");
		}
		return dataSource;
	}
	
	@Getter
	@Setter
	public static class BaseDataSourcProperties {
		/**
		 * JDBC url of the database.
		 */
		private String url;

		/**
		 * Login user of the database.
		 */
		private String username;

		/**
		 * Login password of the database.
		 */
		private String password;
		
		/**
		 * 插件
		 */
		private String filters;
		
		/**
		 * 最大并发连接数
		 */
		private int maxActive;
		
		/**
		 * 初始化连接数量
		 */
		private int initialSize;
		
		/**
		 * 最小空闲连接数
		 */
		private int minIdle;
	}
	
	@ConfigurationProperties(prefix = "druid.datasource")
	public static class DruidDataSourcProperties extends BaseDataSourcProperties {}
}